<?php

namespace app\api\controller\carbon\knowledge;

use app\common\controller\Api;
use think\Db;

/**
 * 核算接口
 */
class Share extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取科普知识列表
     */
    public function index($user_id = 0)
    {
        $where = [];
        if ($user_id != 0) {
            $where = array(
                'user_id' => $user_id
            );
        }
        $list = model('app\admin\model\carbon\knowledge\share\Info')
            ->where($where)
            ->paginate()
            ->each(function ($qita, $key) {
                $qita->zan_num = model('app\admin\model\carbon\knowledge\share\like\Log')->where("share_id", $qita->id)->count();
                $Log = model('app\admin\model\carbon\knowledge\share\like\Log')->where("share_id", $qita->id)->where("user_id", $this->auth->id)->find();
                $qita->zan_state = false;
                if ($Log) {
                    $qita->zan_state = true;
                }
            });
        $this->success('获取成功', $list);
    }

    /**
     * 分享
     */
    public function postssubmit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params['user_id'] = $this->auth->id;
            $params['create_time'] = time();
            $record =  model('app\admin\model\carbon\knowledge\share\Info')->insert($params);
            if ($record) {
                $this->success('提交成功');
            }
            $this->error('提交失败');
        }
        $this->error('非法请求');
    }
    /**
     * 点赞
     */
    public function postsLikes($share_id)
    {
        $Likes =  model('app\admin\model\carbon\knowledge\share\like\Log')->where("share_id", $share_id)->where("user_id", $this->auth->id)->find();
        if ($Likes) {
            $delete = model('app\admin\model\carbon\knowledge\share\like\Log')->where("share_id", $share_id)->where("user_id", $this->auth->id)->delete();
            if ($delete) {
                $this->success('删除成功');
            }
        } else {
            $insert = model('app\admin\model\carbon\knowledge\share\like\Log')->insert(["share_id" => $share_id, "user_id" => $this->auth->id]);
            if ($insert) {
                $this->success('点赞成功');
            }
        }
        $this->error('操作失败');
    }
}
